/**
 * API使用示例
 * 展示如何在Vue组件中使用API服务
 */

import { ref, reactive, onMounted } from 'vue';
import {
  AuthService,
  HomeService,
  StudyService,
  DetectionService,
  GameService,
  DailyService,
  NotificationService,
  StatisticsService,
  UploadService
} from '@/api/services';

// ==================== 首页组件示例 ====================

export function useHomeData() {
  const homeData = reactive({
    banners: [],
    functions: [],
    recommendations: [],
    activities: [],
    loading: false
  });

  const loadData = async () => {
    homeData.loading = true;
    try {
      const data = await HomeService.loadHomeData();
      Object.assign(homeData, data);
    } finally {
      homeData.loading = false;
    }
  };

  onMounted(() => {
    loadData();
  });

  return {
    homeData,
    loadData
  };
}

// ==================== 用户认证示例 ====================

export function useAuth() {
  const user = ref(null);
  const loading = ref(false);

  const login = async (username: string, password: string) => {
    loading.value = true;
    try {
      const result = await AuthService.login({ username, password });
      if (result) {
        user.value = result.userInfo;
        // 保存token到本地存储
        localStorage.setItem('token', result.token);
        return true;
      }
      return false;
    } finally {
      loading.value = false;
    }
  };

  const register = async (data: {
    username: string;
    password: string;
    nickname: string;
    phone: string;
    verifyCode: string;
  }) => {
    loading.value = true;
    try {
      return await AuthService.register(data);
    } finally {
      loading.value = false;
    }
  };

  const getUserInfo = async () => {
    const userInfo = await AuthService.getUserProfile();
    if (userInfo) {
      user.value = userInfo;
    }
    return userInfo;
  };

  return {
    user,
    loading,
    login,
    register,
    getUserInfo
  };
}

// ==================== 学习中心示例 ====================

export function useStudyCenter() {
  const studyData = reactive({
    categories: [],
    courses: [],
    loading: false
  });

  const searchResults = ref([]);
  const searchLoading = ref(false);

  const loadStudyData = async () => {
    studyData.loading = true;
    try {
      const data = await StudyService.loadStudyData();
      Object.assign(studyData, data);
    } finally {
      studyData.loading = false;
    }
  };

  const searchCourses = async (keyword: string, filters?: any) => {
    if (!keyword.trim()) return;
    
    searchLoading.value = true;
    try {
      const result = await StudyService.searchCourses(keyword, filters);
      searchResults.value = result.list;
    } finally {
      searchLoading.value = false;
    }
  };

  return {
    studyData,
    searchResults,
    searchLoading,
    loadStudyData,
    searchCourses
  };
}

// ==================== 语音检测示例 ====================

export function useVoiceDetection() {
  const detectionTexts = ref([]);
  const currentText = ref(null);
  const evaluationResult = ref(null);
  const history = ref([]);
  const loading = ref(false);

  const loadTexts = async (filters?: { level?: string; category?: string }) => {
    loading.value = true;
    try {
      detectionTexts.value = await DetectionService.getDetectionTexts(filters);
      if (detectionTexts.value.length > 0) {
        currentText.value = detectionTexts.value[0];
      }
    } finally {
      loading.value = false;
    }
  };

  const submitEvaluation = async (audioBlob: Blob, duration: number) => {
    if (!currentText.value) return null;
    
    const result = await DetectionService.submitEvaluation(
      currentText.value.id,
      audioBlob,
      duration
    );
    
    if (result) {
      evaluationResult.value = result;
    }
    
    return result;
  };

  const loadHistory = async (page: number = 1, limit: number = 10) => {
    const result = await DetectionService.getHistory({ page, limit });
    history.value = result.list;
    return result;
  };

  return {
    detectionTexts,
    currentText,
    evaluationResult,
    history,
    loading,
    loadTexts,
    submitEvaluation,
    loadHistory
  };
}

// ==================== 小游戏示例 ====================

export function useGame() {
  const gameContents = ref([]);
  const currentContent = ref(null);
  const gameResult = ref(null);
  const records = ref([]);
  const loading = ref(false);

  const loadGameContents = async (filters?: { level?: string; category?: string }) => {
    loading.value = true;
    try {
      gameContents.value = await GameService.getGameContents(filters);
      if (gameContents.value.length > 0) {
        currentContent.value = gameContents.value[0];
      }
    } finally {
      loading.value = false;
    }
  };

  const submitGameResult = async (audioBlob: Blob, duration: number) => {
    if (!currentContent.value) return null;
    
    const result = await GameService.submitGameResult(
      currentContent.value.id,
      audioBlob,
      duration
    );
    
    if (result) {
      gameResult.value = result;
    }
    
    return result;
  };

  const loadRecords = async (page: number = 1, limit: number = 10) => {
    const result = await GameService.getGameRecords({ page, limit });
    records.value = result.list;
    return result;
  };

  const nextContent = () => {
    const currentIndex = gameContents.value.findIndex(
      item => item.id === currentContent.value?.id
    );
    if (currentIndex < gameContents.value.length - 1) {
      currentContent.value = gameContents.value[currentIndex + 1];
      gameResult.value = null; // 重置结果
    }
  };

  return {
    gameContents,
    currentContent,
    gameResult,
    records,
    loading,
    loadGameContents,
    submitGameResult,
    loadRecords,
    nextContent
  };
}

// ==================== 每日一句示例 ====================

export function useDailySentence() {
  const dailySentence = ref(null);
  const submissionResult = ref(null);
  const history = ref([]);
  const loading = ref(false);

  const loadTodaySentence = async () => {
    loading.value = true;
    try {
      dailySentence.value = await DailyService.getDailySentence();
    } finally {
      loading.value = false;
    }
  };

  const submitReading = async (videoBlob: Blob, duration: number) => {
    if (!dailySentence.value) return null;
    
    const result = await DailyService.submitDailyReading(
      dailySentence.value.id,
      videoBlob,
      duration
    );
    
    if (result) {
      submissionResult.value = result;
    }
    
    return result;
  };

  const loadHistory = async (page: number = 1, limit: number = 10, month?: string) => {
    const result = await DailyService.getDailyHistory({ page, limit, month });
    history.value = result.list;
    return result;
  };

  return {
    dailySentence,
    submissionResult,
    history,
    loading,
    loadTodaySentence,
    submitReading,
    loadHistory
  };
}

// ==================== 通知示例 ====================

export function useNotifications() {
  const notifications = ref([]);
  const unreadCount = ref(0);
  const loading = ref(false);

  const loadNotifications = async (params: {
    page?: number;
    limit?: number;
    type?: string;
    status?: string;
  } = {}) => {
    loading.value = true;
    try {
      const result = await NotificationService.getNotifications({
        page: 1,
        limit: 20,
        ...params
      });
      notifications.value = result.list;
      unreadCount.value = result.unreadCount;
    } finally {
      loading.value = false;
    }
  };

  const markAsRead = async (id: number) => {
    const success = await NotificationService.markAsRead(id);
    if (success) {
      // 更新本地状态
      const notification = notifications.value.find(n => n.id === id);
      if (notification && notification.status === 'unread') {
        notification.status = 'read';
        unreadCount.value = Math.max(0, unreadCount.value - 1);
      }
    }
    return success;
  };

  return {
    notifications,
    unreadCount,
    loading,
    loadNotifications,
    markAsRead
  };
}

// ==================== 统计数据示例 ====================

export function useStatistics() {
  const studyStats = ref(null);
  const userStats = ref(null);
  const loading = ref(false);

  const loadStudyStatistics = async (period: string = 'week') => {
    loading.value = true;
    try {
      studyStats.value = await StatisticsService.getStudyStatistics(period);
    } finally {
      loading.value = false;
    }
  };

  const loadUserStatistics = async () => {
    userStats.value = await StatisticsService.getUserStatistics();
  };

  return {
    studyStats,
    userStats,
    loading,
    loadStudyStatistics,
    loadUserStatistics
  };
}
